package com.damai.mvc.view.imple;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.citywithincity.api.ApiConfig;
import com.citywithincity.api.entities.Customer;
import com.citywithincity.api.utils.ApiUtil;
import com.citywithincity.crypt.CryptFactory;
import com.citywithincity.crypt.IDataCrypt;
import com.citywithincity.utils.JsonUtil;
import com.damai.action.IAction;
import com.damai.action.IRender;

class EncRender implements IRender<Object> {
	@SuppressWarnings("rawtypes")
	public static final IRender DEFAULT = new EncRender();
	private IDataCrypt crypt = CryptFactory.getDataCrypt();
	
	
	private EncRender() {
		
	}
	
	
	@Override
	public void render(IAction action,Object data, HttpServletRequest request, HttpServletResponse response) throws IOException {
		String value = JsonUtil.success(data);
		if(ApiConfig.out){
			ApiConfig.info(value);
		}
		int time = (Integer) request.getAttribute(ApiUtil.time);
		if(time < 0){
			response.getWriter().print(value);
		}else{
			Customer customer = (Customer) request.getAttribute("customer");
			int startIndex = 16 - time % 16;
			//
			try {
				response.getOutputStream().write(crypt.encript(value.getBytes("UTF-8"),
						customer.getKey().substring(startIndex, startIndex + 16).getBytes()));
			} catch (Exception e) {
				response.getOutputStream().print(JsonUtil.alert("请稍后重试"));
			}
		}
		
	}

}
